package com.example.administrator.mypictureshow;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.example.administrator.adapter.AlbumContentAdapter;
import com.example.administrator.bean.AlbumFolder;
import com.example.administrator.bean.AlbumImage;
import com.example.administrator.impl.OnCompatCompoundCheckListener;
import com.example.administrator.impl.OnCompatItemClickListener;
import com.example.administrator.utils.AlbumScanner;
import com.example.administrator.utils.DisplayUtils;
import com.example.administrator.view.PhotoAlbumDialog;
import com.example.administrator.utils.Poster;
import com.example.administrator.view.PreviewDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2018\7\30 0030.
 */

public class AlbumActivity extends AppCompatActivity {

    private RecyclerView album_recycle;
    private AlbumContentAdapter mAlbumContentAdapter;
    private List<AlbumFolder> mAlbumFolders;//手机相册图片数据
    private List<AlbumImage> mCheckedImages = new ArrayList<>();//选中图片数据
    private List<AlbumImage> mTempCheckedImages;
    private int mCheckFolderIndex;

    private Button btn_finish;//完成按钮
    private Button btn_switch_dir;//相册选择按钮
    private Button btn_preview;//预览图片

    private int mAllowSelectCount = 9;

    private static ExecutorService sRunnableExecutor = Executors.newSingleThreadExecutor();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album);
        DisplayUtils.initScreen(this);
        initView();
        initData();
    }

    private void initView() {
        album_recycle = (RecyclerView) this.findViewById(R.id.album_recycle);
        btn_finish = (Button)this.findViewById(R.id.btn_finish);
        btn_switch_dir = (Button) this.findViewById(R.id.btn_switch_dir);
        btn_preview = (Button) this.findViewById(R.id.btn_preview);
        initializeContent();

    }

    private void initData() {
        //扫描本地图片文件
        sRunnableExecutor.execute(scanner);

        btn_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                ArrayList<String> pathList = new ArrayList<>();
                for (AlbumImage albumImage : mCheckedImages) {
                    pathList.add(albumImage.getPath());
                }
                intent.putStringArrayListExtra("pathList", pathList);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        btn_switch_dir.setOnClickListener(mSwitchDirClick);
        btn_preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckedImages.size() == 0)
                    return;
                mTempCheckedImages = new ArrayList<>(mCheckedImages);
                Collections.copy(mTempCheckedImages, mCheckedImages);

                PreviewDialog preview = new PreviewDialog(AlbumActivity.this,R.style.dialogAll);
                preview.setPreviewData(mTempCheckedImages, new OnCompatCompoundCheckListener() {
                    @Override
                    public void onCheck(CompoundButton compoundButton, int position, boolean isChecked) {
                        AlbumImage albumImage = mTempCheckedImages.get(position);
                        albumImage.setChecked(isChecked);
                        int i = mAlbumFolders.get(mCheckFolderIndex).getPhotos().indexOf(albumImage);
                        if (i != -1) {mAlbumContentAdapter.notifyDataSetChanged();}
                        if (!isChecked){
                            mCheckedImages.remove(albumImage);
                        }
                    }
                });

                preview.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (mTempCheckedImages != null) {
                            mTempCheckedImages.clear();
                            mTempCheckedImages = null;
                        }
                    }
                });
                preview.show();
            }
        });
    }

    /**
     * Initialize content.
     */
    private void initializeContent() {
        album_recycle.setHasFixedSize(true);
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(this, 3);
        album_recycle.setLayoutManager(mGridLayoutManager);
        album_recycle.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                if (position % 2 == 0)
                    outRect.set(2, 2, 2, 0);
                else
                    outRect.set(0, 2, 2, 0);
            }
        });

        mAlbumContentAdapter = new AlbumContentAdapter(this);
//        mAlbumContentAdapter.setItemClickListener(new OnCompatItemClickListener() {
//            @Override
//            public void onItemClick(View view, int position) {
//                ArrayList<AlbumImage> albumImages = mAlbumFolders.get(mCheckFolderIndex).getPhotos();
//                dismissPreviewDialog();
//                mAlbumPreviewDialog = new AlbumPreviewDialog(AlbumActivity.this, mToolBarColor, albumImages, mPreviewFolderCheckListener, position, contentHeight);
//                mAlbumPreviewDialog.show();
//            }
//        });
        mAlbumContentAdapter.setOnCheckListener(mContentCheckListener);
        album_recycle.setAdapter(mAlbumContentAdapter);
    }

    /**
     * 切换文件夹按钮被点击。
     */
    private View.OnClickListener mSwitchDirClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final PhotoAlbumDialog dialog = new PhotoAlbumDialog(AlbumActivity.this,R.style.dialogAll);
            dialog.setDialogData(mAlbumFolders, new OnCompatItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    //展示某一文件夹图片文件夹
                    showAlbum(position);
                }
            });
            dialog.show();
        }
    };

    /**
     * Scan image.
     */
    private Runnable scanner = new Runnable() {
        @Override
        public void run() {
            mAlbumFolders = AlbumScanner.getInstance().getPhotoAlbum(AlbumActivity.this);
            Poster.getInstance().post(initialize);
        }
    };
    /**
     * Init ui.
     */
    private Runnable initialize = new Runnable() {
        @Override
        public void run() {
            if (!AlbumActivity.this.isFinishing()) {
                showAlbum(0);
            } else {
                mAlbumFolders.clear();
                mAlbumFolders = null;
            }
        }
    };
    /**
     * 显示某个文件夹的图片。
     *
     * @param index 选中的文件夹的item。
     */
    private void showAlbum(int index) {
        mCheckFolderIndex = index;
        AlbumFolder albumFolder = mAlbumFolders.get(index);
//        mBtnSwitchFolder.setText(albumFolder.getName());
        mAlbumContentAdapter.notifyDataSetChanged(albumFolder.getPhotos());
//        mGridLayoutManager.scrollToPosition(0);
    }

    /**
     * 选中监听。
     */
    private OnCompatCompoundCheckListener mContentCheckListener = new OnCompatCompoundCheckListener() {
        @Override
        public void onCheck(CompoundButton compoundButton, int position, boolean isChecked) {
            AlbumImage albumImage = mAlbumFolders.get(mCheckFolderIndex).getPhotos().get(position);
            albumImage.setChecked(isChecked);
            if (isChecked) {
                if (!mCheckedImages.contains(albumImage))
                    mCheckedImages.add(albumImage);
            } else {
                mCheckedImages.remove(albumImage);
            }

            int hasCheckSize = mCheckedImages.size();
            if (hasCheckSize > mAllowSelectCount) {
                String hint = "你最多可以选择"+mAllowSelectCount+"张图片";
                Toast.makeText(AlbumActivity.this, String.format(Locale.getDefault(), hint, mAllowSelectCount), Toast.LENGTH_LONG).show();
                mCheckedImages.remove(albumImage);
                compoundButton.setChecked(false);
                albumImage.setChecked(false);
            } else {
                setPreviewCount(hasCheckSize);
            }
        }
    };
    //设置完成数量
    private void setPreviewCount(int selectCount){
        btn_finish.setText("完成（"+selectCount+"/"+mAllowSelectCount+")");
    }
}
